package com.xxl.job.admin.controller;

import com.job.common.DTO.JobInfoDTO;
import com.job.common.constant.OpenAPIConstant;
import com.job.common.utils.TokenUtils;
import com.xxl.job.admin.core.thread.JobTriggerPoolHelper;
import com.xxl.job.admin.core.trigger.TriggerTypeEnum;
import com.xxl.job.admin.service.XxlJobService;
import com.xxl.job.admin.utils.IpUtil;
import com.xxl.job.core.biz.model.ReturnT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

/**
 * @author songsong
 * @version 1.0
 * @date 2022/12/20 10:43
 **/
@Controller
@RequestMapping(OpenAPIConstant.WEB_PATH)
public class JobOpenApiController {
    @Autowired
    XxlJobService xxlJobService;

    @RequestMapping(OpenAPIConstant.GET_TOKEN)
    @ResponseBody
    public ReturnT<String> getToken(HttpServletRequest request){
        String ip = IpUtil.getIpAddress(request);
        String token = UUID.randomUUID().toString();
        TokenUtils.ipTokenMap.putIfAbsent(ip, token);
        TokenUtils.ipTimeMap.putIfAbsent(ip,System.currentTimeMillis());
        return new ReturnT(token);
    }
    @RequestMapping(OpenAPIConstant.RUN_JOB)
    @ResponseBody
    public ReturnT<String> run(HttpServletRequest request,int id, String executorParam, String addressList){

        JobTriggerPoolHelper.trigger(id, TriggerTypeEnum.API, -1, null, executorParam, addressList);
        return ReturnT.SUCCESS;
    }

    @RequestMapping(OpenAPIConstant.FETCH_ALL_JOB)
    @ResponseBody
    public ReturnT<List<JobInfoDTO>> getAllRunJob(){
        return new ReturnT(xxlJobService.getAllRunJob());
    }
}
